package com.app.xinfadi.db;

import android.content.Context;

import com.app.xinfadi.green_dao.dao.ProductBeanDao;
import com.app.xinfadi.green_dao.model.ProductBean;


import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;


/**
 * Function:
 * <br/>
 * Create on:2015/9/17 9:59
 * <br/>
 * Author:WuTengFei
 */
public class ProductBeanDbHelper {
    private static ProductBeanDbHelper sInstance = null;
    private static final String TAG = ProductBeanDbHelper.class.getSimpleName();
    private ProductBeanDao choosesDao;

    public synchronized static ProductBeanDbHelper getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new ProductBeanDbHelper(context);
        }
        return sInstance;
    }

    public ProductBeanDbHelper(Context context) {
        choosesDao = DBHelper.getInstance(context).getDaoSession().getProductBeanDao();
    }

    /**
     * 更新选项
     */
    public void insertOrUpdate(ProductBean product) {
        ProductBean mChooses;
        if (product != null) {
            if (isExist(product.getID() + "")) {
                mChooses = getProduct(product.get_id() + "");
//                mChooses.set(product.getChoose());
            }
        }
    }

    public void insert(ProductBean chooses) {
        choosesDao.insert(chooses);
    }

    /**
     * 删除指定道题目所有选项
     *
     * @param record_id
     */
    public void delete(String record_id) {
//        LogUtil.e(TAG, "recod_id:" + record_id);
        QueryBuilder qb = choosesDao.queryBuilder();
        qb.where(ProductBeanDao.Properties.ID.eq(record_id));
        qb.buildDelete().executeDeleteWithoutDetachingEntities();
    }

    public void deleteAll() {
        choosesDao.deleteAll();
    }

    /**
     * 是否存在改选项
     *
     * @return
     */
    public boolean isExist(String id) {
        QueryBuilder qb = choosesDao.queryBuilder();
        qb.where(ProductBeanDao.Properties.ID.eq(id));
        long count = qb.buildCount().count();
        return count > 0;
    }

    /**
     * 获取该 Chooses
     *
     * @return
     */
    public ProductBean getProduct(String id) {
        QueryBuilder qb = choosesDao.queryBuilder();
        qb.where(ProductBeanDao.Properties.ID.eq(id));
        List<ProductBean> chooseList = qb.list();
        if (chooseList.size() > 0) {
            return chooseList.get(0);
        } else
            return null;
    }

    /**
     * 0
     * @param parent_id
     * @return
     */
    public List<ProductBean> getProductAll(String parent_id) {
        QueryBuilder qb = choosesDao.queryBuilder();
        qb.where(ProductBeanDao.Properties.PARENT_ID.eq(parent_id));
        List<ProductBean> chooseList = qb.list();
        return chooseList;
    }


}
